package com.csw.shuanfa.utils.id;

import com.csw.shuanfa.GlobalConfig.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Date;

@Component
public class DailyCounterWithRedisTemplate {
    private static StringRedisTemplate stringRedisTemplate;

    public DailyCounterWithRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        DailyCounterWithRedisTemplate.stringRedisTemplate = stringRedisTemplate;
    }


    public static long incrementDailyCounter(String key) {
        if (StringUtils.isEmpty(key)) {
            throw new BusinessException("key必传");
        }
        Date today = new Date();
        key = key + today.getDate();
        Long increment = stringRedisTemplate.opsForValue().increment(key);
        stringRedisTemplate.expire(key, Duration.ofDays(1)); // 设置过期时间为一天（24 小时）
        return increment;
    }
}
